<template>
  <div class="app-container">
    <cus-wraper>
      <cus-filter-wraper>

        <el-tag>选择所属项目:</el-tag>
        <br><br>
        <el-table max-height="500" :data="formData.applicationList" highlight-current-row
                  @row-click="rowClick">
          <el-table-column label="项目ID" width="200">
            <template slot-scope="scope">
              <el-radio :label="scope.row.id" v-model="formData.applicationId"/>
            </template>
          </el-table-column>
          <el-table-column label="项目名称" prop="name" min-width="200"/>
          <el-table-column label="备注" prop="remark" min-width="500"/>
        </el-table>
        <br>
        <el-form ref="elForm" :model="formData" :rules="rules" size="small">
          <el-form-item label="所属项目ID" prop="applicationId" label-width="100px">
            <el-input v-model="formData.applicationId" placeholder="请选择所属项目ID" show-word-limit readonly
                      clearable :style="{width: '100%'}"></el-input>
          </el-form-item>

          <el-form-item label="创建类型" prop="jarSource" label-width="100px">
            <el-select v-model="formData.jarSource" placeholder="请选择创建类型">
              <el-option label="git创建" value="git"></el-option>
              <el-option label="自定义上传" value="upload"></el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="git项目列表" prop="gitPro" v-if="formData.jarSource==='git'" label-width="100px">
            <el-select v-model="formData.gitPro" placeholder="请选择git项目" @change="gitProChange" style="min-width: 500px">
              <el-option v-for="item in formData.gitProjectList" :key="item.id" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="模块列表" prop="gitModule" v-if="formData.jarSource==='git'" label-width="100px">
            <el-select v-model="formData.gitModule" placeholder="请选择模块儿" @change="moduleChange"
                       style="min-width: 500px">
              <el-option v-for="item in formData.gitModuleList" :key="item.id" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="jar包列表" prop="gitJarId" v-if="formData.jarSource==='git'" label-width="100px">
            <el-select v-model="formData.gitJarId" placeholder="请选择jar包" style="min-width: 500px">
              <el-option v-for="item in formData.gitJarList" :key="item.id" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="上传文件" style="margin-left: 50px" v-if="formData.jarSource==='upload'">
            <el-upload
                class="upload-demo"
                ref="uploadJarFile"
                accept=".jar"
                :file-list="formData.fileList"
                :show-file-list="true"
                :auto-upload="false"
                :on-remove="handelRemove"
                :before-upload="beforeUpload"
                :on-change="fileChange"
                :http-request="HttpUploadPost"
                action="">
              <div slot="tip" class="el-upload__tip">只能上传jar文件</div>
              <el-button slot="trigger" size="small" plain>选择文件</el-button>
              <el-button size="small" type="primary" @click="uploadSummit" :loading="isUpload">立即上传</el-button>
            </el-upload>

          </el-form-item>
          <el-form-item label="文件名" label-width="110px" prop="fileName" v-if="formData.jarSource==='upload'">
            <el-input v-model="formData.fileName" disabled></el-input>
          </el-form-item>
          <el-form-item label="临时目录" label-width="110px" prop="tmpPath" v-if="formData.jarSource==='upload'">
            <el-input v-model="formData.tmpPath" disabled></el-input>
          </el-form-item>

          <el-form-item label="文件类型" prop="jarType" label-width="100px">
            <el-select v-model="formData.jarType" placeholder="请选择文件类型">
              <el-option label="flink任务" value="task"/>
              <el-option label="自定义函数" value="udf"/>
              <el-option label="其他依赖" value="dep"/>
            </el-select>
          </el-form-item>

          <el-form-item label="main入口" prop="mainClass" label-width="100px" v-if="formData.jarType==='task'">
            <el-input v-model="formData.mainClass" placeholder="请输入main入口" show-word-limit
                      clearable :style="{width: '100%'}"></el-input>
          </el-form-item>

          <el-form-item label="udf函数名" prop="funcName" label-width="100px" v-if="formData.jarType==='udf'">
            <el-input v-model="formData.funcName" placeholder="请输入udf函数名" show-word-limit
                      clearable :style="{width: '100%'}"></el-input>
          </el-form-item>


          <el-form-item label="备注" label-width="100px">
            <el-input type="textarea" v-model="formData.remark"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="isSave">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>

      </cus-filter-wraper>
    </cus-wraper>
  </div>
</template>

<script>
import axios from 'axios'
import {baseUrl} from "@/utils/ruoyi";
import {getToken} from "@/utils/auth";
import {removeHdfsTmp,addJarmanagement} from "@/api/resource/jarmanagement";

export default {
  components: {},
  props: {
    formData: {
      type: Object,
      default: {}
    },

    gitProjectList: {
      type: Array,
      default: []
    },

    moduleList: {
      type: Array,
      default: []
    },
    moduleJarList: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      isSave: false,
      isUpload: false,
      rules: {
        applicationId: [{
          required: true,
          message: '所属项目不能为空',
          trigger: 'blur'
        }],
        jarSource: [{
          required: true,
          message: '创建类型不能为空',
          trigger: 'blur'
        }],
        gitPro: [{
          required: true,
          message: '创建类型不能为空',
          trigger: 'blur'
        }],
        gitJarId: [{
          required: true,
          message: 'git项目不能为空',
          trigger: 'blur'
        }],
        gitModule: [{
          required: true,
          message: 'git模块不能为空',
          trigger: 'blur'
        }],

        jarType: [{
          required: true,
          message: '文件类型不能为空',
          trigger: 'blur'
        }],

        mainClass: [{
          required: true,
          message: 'main入口不能为空',
          trigger: 'blur'
        }],

        funcName: [{
          required: true,
          message: 'udf函数名不能为空',
          trigger: 'blur'
        }],
        fileName: [{
          required: true,
          message: '文件名不能为空',
          trigger: 'blur'
        }],
        tmpPath: [{
          required: true,
          message: '临时目录不能为空',
          trigger: 'blur'
        }]
      },
    }
  },
  methods: {
    rowClick(row) {
      this.formData.applicationId = row.id;
      this.setProjectList(this.formData.applicationId);
    },
    setProjectList(appId) {
      this.formData.gitProjectList = [];
      this.formData.gitPro = '';
      this.formData.gitModuleList = [];
      this.formData.gitModule = '';
      this.formData.gitJarList = [];
      this.formData.gitJarId = '';
      if (this.gitProjectList.length > 0) {
        this.formData.gitProjectList = this.gitProjectList.filter(item => item.applicationId === appId)
      }
    },

    /**
     * 获取git模块儿信息
     * @param value
     */
    gitProChange(value) {
      if (this.formData.jarSource === 'git') {
        this.formData.gitModuleList = [];
        this.formData.gitModule = '';
        this.formData.gitJarList = [];
        this.formData.gitJarId = '';
        if (this.moduleList.length > 0) {
          this.formData.gitModuleList = this.moduleList.filter(item => item.flinkProjectId === value)
        }
      }
    },

    /**
     * 获取模块儿jar
     */
    moduleChange(value) {
      if (this.formData.jarSource === 'git') {
        this.formData.gitJarList = [];
        this.formData.gitJarId = '';
        if (this.moduleJarList.length > 0) {
          this.formData.gitJarList = this.moduleJarList.filter(item => item.moduleId === value)
        }
      }
    },


    /**
     * 文件上传移除
     */
    handelRemove(file, fileList) {
      this.formData.fileList = fileList;
      this.formData.fileName = '';
    },

    /**
     * 上传前检查
     * @param file
     */
    beforeUpload(file) {

      if (this.formData.applicationId === '') {
        this.$message.warning('请选择所属项目！')
        return
      }

      let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (extension !== 'jar') {
        this.$notify.warning({
          title: '警告',
          message: `只能上传jar文件`
        });
      } else {
        this.formData.fileName = file.name;
      }
    },

    /**
     * 文件发生改变时候
     * @param file
     * @param fileList
     */
    fileChange(file, fileList) {

      this.formData.fileName = file.name;
      this.formData.tmpPath = '';
      if (fileList.length > 0) {
        this.formData.fileList = [fileList[fileList.length - 1]]
      }
    },

    HttpUploadPost(param) {
      let file = param.file;
      let file_form = new FormData();
      file_form.append("file", file);
      console.log("上传的文件", file)
      file_form.append("applicationId", this.formData.applicationId)
      this.isUpload = true;
      axios({
        url: process.env.VUE_APP_BASE_API + "/resource/jarmanagement/createUploadFile", // 上传的图片服务器地址
        method: "POST",
        headers: {
          Authorization: "Bearer " + getToken()
        },
        data: file_form,
      }).then((res) => {
        this.formData.tmpPath = res.data.data
        this.isUpload = false;
      }).catch((err) => {
        this.$message.error('上传文件失败：' + err)
        this.isUpload = false;
      });
    },
    uploadSummit() {
      if (this.formData.fileList !== undefined && this.formData.fileList.length > 0) {
        console.log("开始上传文件", this.fileList)
        this.$refs.uploadJarFile.submit();
        this.formData.fileList = [];
      } else {
        this.$message.warning("没有可上传的文件！");
        return false;
      }
    },

    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.isSave=true;
        addJarmanagement(this.formData).then(res=>{
          this.isSave=false;
          this.$message.success('保存成功')
          this.resetForm();
          this.$emit('saveOk')
        })
      })
    },
    /**
     * 重置
     */
    resetForm: function () {
      if (this.isUpload || this.isSave) {
        this.$message.warning('当前有正在执行的操作不能重置');
        return
      }
      this.removeHdfsTmp();
      this.$refs['elForm'].resetFields()
    },

    removeHdfsTmp: function () {
      if (this.formData.applicationId !== '' && this.formData.tmpPath !== '' && this.formData.tmpPath !== undefined
          && this.formData.tmpPath !== null) {
        const data = {'applicationId': this.formData.applicationId, 'uploadPath': this.formData.tmpPath}
        removeHdfsTmp(data)
      }
    }

  },
  mounted() {
  },
  created() {
  }
}
</script>

<style scoped>

</style>